package org.middleware.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;
import java.io.File;

/**
 * 文件存储路径的配置，目前只用来存储头像
 */
@Slf4j
@Configuration
public class FileUploadConfig implements WebMvcConfigurer {
    @Value("${file.upload.path}")
    private String avatarUploadPath;

    @Value("${file.upload.access-url}")
    private String avatarAccessUrl;

    @PostConstruct
    public void init() {
        // 创建上传目录
        File uploadDir = new File(avatarUploadPath);
        if (!uploadDir.exists()) {
            boolean created = uploadDir.mkdirs();
            if (created) {
                log.info("创建上传目录: " + uploadDir.getAbsolutePath());
            }
        }
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(avatarAccessUrl + "**")
                .addResourceLocations("file:" + avatarUploadPath);
    }

    public String getAvatarUploadPath() {
        return avatarUploadPath;
    }

    public String getAvatarAccessUrl() {
        return avatarAccessUrl;
    }
}
